package com.gitee.sop.message.sms;

import com.gitee.sop.message.Sender;
import com.gitee.sop.message.manager.SenderManagerServiceImpl;
import com.gitee.sop.message.util.HttpUtil;
import com.gitee.sop.message.util.MapUtil;
import com.gitee.sop.message.util.scheduler.SchedulerUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Admin
 */
public class RongTongDaSmsSender implements Sender {

    @Override
    public boolean send(String type,String receiver, String message, Map<String, Object> senderParameter) throws Exception {
        String title = senderParameter.get("rcompany").toString();
        if (SenderManagerServiceImpl.SenderEnum.sms.getType().equals(type)) {
            title = StringUtils.isNotBlank(title) ? "【" + title + "】" : "【蓝星云开放平台】";
        } else if (SenderManagerServiceImpl.SenderEnum.email.getType().equals(type)) {
            title = StringUtils.isNotBlank(title) ? title : "蓝星云开放平台";
        }
        Map<String, String> parameterMap = new HashMap<>(2);
        parameterMap.put("pn", receiver);
        parameterMap.put("msg", title + message);
        parameterMap.put("account", senderParameter.get("raccount") + "");
        parameterMap.put("pswd", senderParameter.get("rpswd") + "");
        Object host = senderParameter.get("rhost");
        Object api = senderParameter.get("rapi");
        HttpUtil.HttpResponse response = null;
        try {
            response = HttpUtil.connection(host.toString() + api.toString()).setParameter(parameterMap).post();
        } catch (Exception e) {
            throw e;
        }
        return true;
    }

    @Override
    public boolean syncSend(String receiver, String message, String title, Map<String, Object> senderParameter) throws Exception {
        SchedulerUtil.schedule(() -> {
            send(receiver, message, title, senderParameter);
        });
        return true;
    }

    @Override
    public Map<String, Object> senderParameterTemplate() {
        return MapUtil.builder().elem("raccount", "账户，由蓉通达后台获取，类似：113913")
                .elem("rpswd", "密码")
                .elem("rhost", "主机地址：由蓉通达提供，类似：http://122.144.203.27:8001")
                .elem("rapi", "api地址：由蓉通达提供，类似：/mt.ashx").build();
    }
}
